package com.zp.self.module.返回xml结构数据.重写序列化方式;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializable;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ：by peng.zeng
 * @date ：Created 2021/5/21 16:28
 * @description ：XML序列化的公共写法
 */
public class XmlJsonSerializableCommon implements JsonSerializable {
    public Map<String,String> attributesMap = new HashMap<>();
    public Map<String,Object> ObjectFieldMap = new HashMap<>();


    @Override
    public void serialize(JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        ToXmlGenerator toXmlGenerator = (ToXmlGenerator) jsonGenerator;
        toXmlGenerator.writeStartObject();

        writeAttributes(toXmlGenerator);
        writeMap(toXmlGenerator);

        toXmlGenerator.writeEndObject();
    }

    private void writeAttributes(ToXmlGenerator gen) throws IOException {
        if (attributesMap.isEmpty())
           return;
        gen.setNextIsAttribute(true);
        for (Map.Entry<String, String> entry : attributesMap.entrySet()) {
            gen.writeFieldName(entry.getKey());
            gen.writeString(entry.getValue());
        }
        gen.setNextIsAttribute(false);
    }

    private void writeMap(ToXmlGenerator gen) throws IOException {
        for (Map.Entry<String, Object> entry : ObjectFieldMap.entrySet()) {
            gen.writeObjectField(entry.getKey(), entry.getValue());
        }
    }

    @Override
    public void serializeWithType(JsonGenerator jsonGenerator, SerializerProvider serializerProvider, TypeSerializer typeSerializer) throws IOException {
        serialize(jsonGenerator, serializerProvider);
    }
}
